<?php

function wowcharsheet_update_toon($realm = '', $name = '') {
  
  
  //wowcharsheet_update_toon_achevements($realm,$name);
  
  // Generate conditional GET headers.
  $headers = array();
    $headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2";
//  $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) .' GMT';

  // Request feed.
  $url = sprintf('http://%s.wowarmory.com/character-sheet.xml?r=%s&n=%s', variable_get('wowcharsheet_country', 'www'), urlencode($realm),urlencode(($name)));
  $result = drupal_http_request($url, $headers);
  //$result->code = 200;
  //$result->data = file_get_contents('C:\Users\ytwater\Downloads\edor-tank.xml');
  
  
  switch ($result->code) {
    case 304:
//      db_query('UPDATE {aggregator_feed} SET checked = %d WHERE fid = %d', time(), $feed['fid']);
//      drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed['title'])));
      break;
    case 301:
    case 200: // Success
    case 302:
    case 307:
      $xml = new SimpleXMLElement($result->data);
      
      /*
      $output .= '<pre>';
      $output .= print_r($xml, true);
      $output .= '</pre>';
		  print $output;
		  die();
      */
			// Error?
			if($xml->characterInfo['errCode'] == 'noCharacter') return FALSE;
      if(!isset($xml->characterInfo->characterTab)) return FALSE;
	
		  $lang = (string)$xml['lang'];
	      
		  $toon->name = (string)$xml->characterInfo->character['name'];
		  $toon->realm = (string)$xml->characterInfo->character['realm'];
	
		  $toon->toon_key = wowcore_getkey($toon->realm, $toon->name);
	
		  $toon->title = (string)$xml->characterInfo->character['title'];
		  $toon->battleGroup = (string)$xml->characterInfo->character['battleGroup'];
		  $toon->guildName = (string)$xml->characterInfo->character['guildName'];
		  //
		  //$toon->guild_nid = $xml->characterInfo->character['name'];
		  //
		  $toon->classId = (int)$xml->characterInfo->character['classId'];
		  $toon->genderId = (int)$xml->characterInfo->character['genderId'];
		  $toon->raceId = (int)$xml->characterInfo->character['raceId'];
		  $toon->factionId = (int)$xml->characterInfo->character['factionId'];
		  $toon->level = (int)$xml->characterInfo->character['level'];
	
	      // Save constants
		  _wowcharsheet_set_constant($lang, 'classId',(int)$xml->characterInfo->character['classId'],(string)$xml->characterInfo->character['class']);
		  _wowcharsheet_set_constant($lang, 'genderId',(int)$xml->characterInfo->character['genderId'],(string)$xml->characterInfo->character['gender']);
		  _wowcharsheet_set_constant($lang, 'raceId',(int)$xml->characterInfo->character['raceId'],(string)$xml->characterInfo->character['race']);
		  _wowcharsheet_set_constant($lang, 'factionId',(int)$xml->characterInfo->character['factionId'],(string)$xml->characterInfo->character['faction']);
      
		  $toon->lifetimehonorablekills = (int)$xml->characterInfo->characterTab->pvp->lifetimehonorablekills['value'];
		  $toon->profession0_name = (string)$xml->characterInfo->characterTab->professions->skill[0]['key'];
		  $toon->profession0_value = (string)$xml->characterInfo->characterTab->professions->skill[0]['value'];
		  $toon->profession0_max = (string)$xml->characterInfo->characterTab->professions->skill[0]['max'];
		  $toon->profession1_name = (string)$xml->characterInfo->characterTab->professions->skill[1]['key'];
		  $toon->profession1_value = (string)$xml->characterInfo->characterTab->professions->skill[1]['value'];
		  $toon->profession1_max = (string)$xml->characterInfo->characterTab->professions->skill[1]['max'];
	
		  if($xml->characterInfo->characterTab->professions->skill[0]['key']) {
		    _wowcharsheet_set_constant($lang, 'professionsKeys',(string)$xml->characterInfo->characterTab->professions->skill[0]['key'],(string)$xml->characterInfo->characterTab->professions->skill[0]['name']);
		  }
	
		  if($xml->characterInfo->characterTab->professions->skill[1]['key']) {
		    _wowcharsheet_set_constant($lang, 'professionsKeys',(string)$xml->characterInfo->characterTab->professions->skill[1]['key'],(string)$xml->characterInfo->characterTab->professions->skill[1]['name']);
	      }
	
		  $tmp = array();
		  convertXmlObjToArr($xml->characterInfo->characterTab->baseStats, $tmp);
		  $tmp2 = array();
		  foreach($tmp as $ele) {
		  	$tmp2[$ele['@name']] = $ele['@attributes'];
		  }
      
      // Check Spec and Sets
      for($i=0;$i<count($xml->characterInfo->characterTab->talentSpecs->talentSpec);$i++) {
        if($xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['active'] == '1') {
          db_query("UPDATE {wowcharsheet_sets} SET active = 0 WHERE toon_key='%s'", $toon->toon_key);
          db_query("DELETE FROM {wowcharsheet_sets} WHERE toon_key = '%s' AND set_id = %d", $toon->toon_key, $xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['group']);
          
          $set->toon_key = $toon->toon_key;
          $set->set_id = $xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['group'];
          $set->icon = $xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['icon'];
          $set->active = 1;
          $set->spec = sprintf("%s (%d/%d/%d)",
            $xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['prim'],
            $xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['treeOne'],
            $xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['treeTwo'],
            $xml->characterInfo->characterTab->talentSpecs->talentSpec[$i]['treeThree']);
          $set->baseStats = $xml->characterInfo->characterTab->baseStats->asXML();
          $set->resistances = $xml->characterInfo->characterTab->baseStats->asXML();
          $set->melee = $xml->characterInfo->characterTab->melee->asXML();
          $set->ranged = $xml->characterInfo->characterTab->ranged->asXML();
          $set->spell = $xml->characterInfo->characterTab->spell->asXML();
          $set->defenses = $xml->characterInfo->characterTab->defenses->asXML();
          $set->items = $xml->characterInfo->characterTab->items->asXML();
          drupal_write_record('wowcharsheet_sets', $set);
        }
      }
	
		  $toon->updated_on_armory = strtotime((string)$xml->characterInfo->character['lastModified']);
		  $toon->updated = time();
	      
		  $res = db_fetch_object(db_query("SELECT toon_key FROM {wowcharsheet_toons} WHERE toon_key = '%s'",$toon->toon_key));
			if($res) {
			  if($toon->added_to_database == 0) $toon->added_to_database = time();

        $ret = drupal_write_record('wowcharsheet_toons',$toon, 'toon_key');
        
  		  if($ret == SAVED_UPDATED) {
          watchdog('content', "%toon_key has been updated", array('%toon_key' => $toon->toon_key));
				  $toon->status = 'SAVED_UPDATED';
        }
			} else {
        $toon->added_to_database = time();
        $ret = drupal_write_record('wowcharsheet_toons',$toon);
        if($ret == SAVED_NEW) {
				  $toon->status = 'SAVED_NEW';
          watchdog('content', "%toon_key has been added to the database", array('%toon_key' => $toon->toon_key));
        }
			}
 		  if($ret === FALSE) {
			  $toon->status = 'FAILED';
        drupal_set_message("An error occured saving $toon->toon_key");
      } else {
        // Add / Update recently added items  TODO: Limit to only attached toons
        $current_items_res = db_query("SELECT * FROM {wowcharsheet_toon_saved_items} WHERE toon_key = '%s'",$toon->toon_key);
        $current_items = array();
        while($ele = db_fetch_object($current_items_res)) {
          $current_items[$ele->item_id] = $ele->icid;
        }
        
        foreach($xml->characterInfo->characterTab->items->item as $item) {
          if(!array_key_exists((integer)$item['id'],$current_items)) {
            $newitem = array(
              'toon_key' => $toon->toon_key,
              'item_id' => (integer)$item['id'],
              'guild_key' => wowcore_getkey($toon->realm,$toon->guildName),
              'date_obtained' => $toon->updated_on_armory,
            );
            drupal_write_record('wowcharsheet_toon_saved_items',$newitem);
            // ping the new item to be sure it's in the cache.
            wowitemcache_item($newitem['item_id']);
          }
        }
        // Do Achevements
        wowcharsheet_update_toon_achevements($toon->realm,$toon->name);

      }
	

      //$output .= '<pre>';
      //$output .= print_r($toon, true);
      //$output .= print_r($xml->characterInfo->characterTab, true);
      //$output .= '</pre>';
      
//      $output .= sprintf('<img src="%s.jpg" width="51" height="51" border="0">', 'http://www.wowarmory.com/images/icons/51x51/' . $xml->characterInfo->characterTab->items->item[0]['icon']);
      
      //$output .= '<a href="http://www.wowhead.com/?item=' . $xml->characterInfo->characterTab->items->item[0]['id'] . '&spell=3003">Thunderfury, Blessed Blade of the Windseeker</a>';

      return $toon;
      break;
    default:
      watchdog('content', 'The feed from %site seems to be broken, due to "%error".', array('%site' => $url, '%error' => $result->code .' '. $result->error), WATCHDOG_WARNING);
      drupal_set_message(t('The feed from %site seems to be broken, because of error "%error".', array('%site' => $url, '%error' => $result->code .' '. $result->error)));
      return;
  }
}

function wowcharsheet_update_guild($realm = '', $name = '', $force = FALSE) {
  
  // Idiot check
  if(($realm == '')||($name == '')) {
    return false;
  }
  
  
  // Generate conditional GET headers.
  $headers = array();
    $headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2";
//  $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) .' GMT';

  // Request feed.
  $url = sprintf('http://%s.wowarmory.com/guild-info.xml?r=%s&n=%s', variable_get('wowcharsheet_country', 'www'), urlencode($realm),urlencode(($name)));
  $result = drupal_http_request($url, $headers);
  //$result->code = 200;
  //$result->data = file_get_contents('C:\Users\ytwater\Documents\guild-info.xml');
  
  switch ($result->code) {
    case 304:
//      db_query('UPDATE {aggregator_feed} SET checked = %d WHERE fid = %d', time(), $feed['fid']);
//      drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed['title'])));
      break;
    case 301:
    case 200: // Success
    case 302:
    case 307:
      $xml = new SimpleXMLElement($result->data);
			
			// Error?
			if($xml->characterInfo['errCode'] == 'noCharacter') return FALSE;
      
	
		  $lang = (string)$xml['lang'];
	      
		  $guild->name = (string)$xml->guildInfo->guildHeader['name'];
		  $guild->realm = (string)$xml->guildInfo->guildHeader['realm'];
			$guild->factionId = (string)$xml->guildInfo->guildHeader['faction'];
	
		  $guild->guild_key = wowcore_getkey($guild->realm, $guild->name);
		  

			
			// See if guild exists in database, add if not.
			$res = db_fetch_object(db_query("SELECT * FROM {wowcharsheet_guilds} WHERE guild_key = '%s'", $guild->guild_key));
			
			if(!$res) {
			  $guild->added_to_database = time();
        $res = db_fetch_object(db_query("SELECT MAX(nid) as maxid FROM {wowcharsheet_guilds}"));
        $guild->nid = $res->maxid + 1;
			  $ret = drupal_write_record('wowcharsheet_guilds',$guild);
        $guild = db_fetch_object(db_query("SELECT * FROM {wowcharsheet_guilds} WHERE guild_key = '%s'", $guild->guild_key));
			} else {
        $guild = $res;
      }
      $guild->updated = time();
		  if($force == TRUE) {
        db_query("UPDATE {wowcharsheet_toons} SET guildName = '', guild_nid = 0 WHERE guild_nid = %d", $guild->nid);
        //db_query("DELETE FROM {wowcharsheet_guilds} WHERE guild_key = '%s'", $guild->guild_key);
      }
      
			// Load existing toons in database.
			$res = db_query("SELECT toon_key,realm,guildName FROM {wowcharsheet_toons} WHERE realm='%s'", $realm);
		  $existing_toons = array();
			while($toon = db_fetch_array($res)) {
				$existing_toons[] = $toon['toon_key'];
			}

			
			// Loop over memebers and create stats
			$members = array();
      $added = 0;
      $updated = 0;
			$cnt = (int)$xml->guildInfo->guild->members['memberCount'];
			foreach($xml->guildInfo->guild->members->character as $member) {//($i=0;$i<$cnt;$i++) {
			  //$member = $xml->guildInfo->guild->members->character[$i];
				unset($toon);
				$toon['guild_nid'] = $guild->nid;
				$toon['toon_key'] = wowcore_getkey($guild->realm, (string)$member['name']);
				$toon['realm'] = $guild->realm;
				$toon['name'] = (string)$member['name'];
        $toon['guildName'] = (string)$guild->name;
        $toon['guild_nid'] = $guild->nid;
				$toon['classId'] = (string)$member['classId'];
				$toon['genderId'] = (string)$member['genderId'];
				$toon['raceId'] = (string)$member['raceId'];
				$toon['level'] = (string)$member['level'];
				$toon['rank'] = (string)$member['rank'];

				$members[] = $toon;
				
        if(!in_array($toon['toon_key'],$existing_toons)) {
          $added++;
          $ret = drupal_write_record('wowcharsheet_toons',$toon);
				} else {
          $updated++;
          $ret = drupal_write_record('wowcharsheet_toons',$toon, 'toon_key');
        }
			}
			$guild->members = $members;

/*      $output .= '<pre>';
      $output .= print_r($guild, true);
      $output .= print_r($xml, true);
      $output .= '</pre>';
		  print $output;
		  die();*/


      drupal_set_message(t('The guild %name on %realm has been updated (%added added, %updated updated)',
        array('%name' => $guild->name, '%realm' => $guild->realm, '%added' => $added, '%updated' => $updated)));

			return $guild;
  }
}

function wowcharsheet_update_toon_achevements($realm,$name) {
  // Generate conditional GET headers.
  $headers = array();
  $headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2";
//  $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) .' GMT';

  // Request feed.
  $url = sprintf('http://www.wowarmory.com/character-achievements.xml?r=%s&cn=%s', urlencode($realm),urlencode($name));
  $result = drupal_http_request($url, $headers);
  
//  $result->code = 200;
//  $result->data = file_get_contents('modules/wowcharsheet/fasemelt.xml');
  
  switch ($result->code) {
    case 304:
//      db_query('UPDATE {aggregator_feed} SET checked = %d WHERE fid = %d', time(), $feed['fid']);
//      drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed['title'])));
      break;
    case 301:
    case 200: // Success
    case 302:
    case 307:
      $xml = new SimpleXMLElement($result->data);
      
      
      if($xml->characterInfo['errCode'] == 'noCharacter') return FALSE;
      if(isset($xml->errorhtml)) return FALSE;
      //if(!isset($xml->characterInfo->characterTab)) return FALSE;
  
      $lang = (string)$xml['lang'];
        
     $output .= '<pre>';
     
     $toon_key = wowcore_getkey($realm,$name);
     
     // Get current achevements
      $res = db_query("SELECT * FROM {wowcharsheet_toon_saved_achevements} WHERE toon_key='%s'", $toon_key);
      $existing_toon_ids = array();
      while($ele = db_fetch_array($res)) {
        $existing_toon_ids[] = $ele['id'];
      }
      $res = db_query("SELECT * FROM {wowcharsheet_toon_achevements}");
      $existing_ids = array();
      while($ele = db_fetch_array($res)) {
        $existing_ids[] = $ele['id'];
      }
     
     // Load Achevement Categories
     $wowcharsheet_achevement_cats = variable_get('wowcharsheet_achevement_cats', array());
     if(!$wowcharsheet_achevement_cats) {
       foreach($xml->achievements->rootCategories->category as $cat) {
         $wowcharsheet_achevement_cats[(integer)$cat['id']] = (string)$cat['name'];
       }
       variable_set('wowcharsheet_achevement_cats', $wowcharsheet_achevement_cats);
     }
     
     
     foreach($xml->achievements->summary->achievement as $ele) {
       $newobj->toon_key = $toon_key;
       $newobj->categoryId = (integer)$ele['categoryId'];
       $newobj->dateCompleted = strtotime((string)$ele['dateCompleted']);
       $newobj->description = (string)$ele['desc'];
       $newobj->icon = (string)$ele['icon'];
       $newobj->id = (integer)$ele['id'];
       $newobj->points = (integer)$ele['points'];
       $newobj->title = (string)$ele['title'];

       if(!in_array($newobj->id,$existing_toon_ids)) {
         drupal_write_record('wowcharsheet_toon_saved_achevements',$newobj);
       }
       $newobj->id = (integer)$ele['id'];
       if(!in_array($newobj->id,$existing_ids)) {
         drupal_write_record('wowcharsheet_toon_achevements',$newobj);
       }
     }
  }
}